package Presentacion;

import ModeloLogicoSistema.AdministradorStock;
import ModeloLogicoSistema.Validacion;
import java.awt.HeadlessException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Veko
 */
public class BuscarEnStock extends javax.swing.JDialog {

    AdministradorStock adm;
    ArrayList<Object[]> productos;
    private int codigo = 0;
    private int descripcion = 1;
    private int cantidadEnStock = 2;

    /**
     * Creates new form BuscarEnStock
     */
    void cargarTabla() {
        try {
            DefaultTableModel modelo = (DefaultTableModel) this.tablaStock.getModel();
            int filas = modelo.getRowCount();

            if (this.productos != null) {
                productos.clear();
            }
            for (int i = 0; i < filas; i++) {
                modelo.removeRow(0);
            }
            productos = this.adm.getTodosLosProductos();
            for (Object[] fila : productos) {
                modelo.addRow(fila);
            }
        } catch (SQLException ex) {
            Logger.getLogger(BuscarEnStock.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public BuscarEnStock(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        try {
            initComponents();
            adm = new AdministradorStock();
            this.setLocationRelativeTo(null);
            
            this.cargarTabla();
            DefaultTableModel modelo = (DefaultTableModel) this.tablaStock.getModel();
            TableRowSorter<TableModel> elQueOrdena = new TableRowSorter<TableModel>(modelo);
            this.tablaStock.setRowSorter(elQueOrdena);
        } catch (SQLException ex) {
            Logger.getLogger(BuscarEnStock.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.setVisible(true);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tablaStock = new javax.swing.JTable();
        btnCancelar = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnDetalle = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Consultar Productos del Stock");

        tablaStock.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Descripción", "Cantidad En Stock"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaStock.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tablaStock);

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/cancelar.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Modificar.png"))); // NOI18N
        btnModificar.setText("Modificar");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        btnDetalle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Detalle.png"))); // NOI18N
        btnDetalle.setText("Detalle");
        this.btnDetalle.setVisible(false);
        btnDetalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetalleActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnDetalle)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnModificar)
                    .addComponent(btnDetalle))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        try {
            DefaultTableModel modelo = (DefaultTableModel) this.tablaStock.getModel();
            Integer fila = this.tablaStock.getSelectedRow();
            Integer cod = (Integer) modelo.getValueAt(fila, this.codigo);
            String desc = JOptionPane.showInputDialog(null, "Código Producto " + cod + "\n Ingrese la descripción del producto", "Modificar Producto", JOptionPane.PLAIN_MESSAGE);
            try {

                if (Validacion.numeroSinLetras(desc)) {
                    JOptionPane.showMessageDialog(null, "El nombre de producto no es válido", "Nombre Inválido", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                if (adm.nombreDeProductoTomado(desc)) {
                    JOptionPane.showMessageDialog(null, "El nombre ingresado, ya existe en memoria para otro producto.\n"
                            + "Verifique si desea modificar este producto, \n"
                            + "o si desea modificar otro producto del stock.", "Nombre existente", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
            } catch (Exception e) {
            }
            if (desc != null) {
                if (!desc.isEmpty()) {

                    adm.modificarDescripcion(cod, desc);
                }
            }
            this.cargarTabla();
        } catch (java.lang.IndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(null, "No selecciono ningún producto del stock", "Atención", JOptionPane.INFORMATION_MESSAGE);
        } catch (HeadlessException | SQLException ex) {
            JOptionPane.showMessageDialog(null, "Hubo un problema al intentar Modificar el producto", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnModificarActionPerformed

    private void btnDetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetalleActionPerformed
        Integer fila;
        Integer cod;
        try {
            fila = this.tablaStock.getSelectedRow();
            cod = (Integer) this.tablaStock.getValueAt(fila, 0);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "No selecciono ningún producto del stock", "Atención", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String nombre = this.tablaStock.getValueAt(fila, 1).toString();
        try {
            DetalleIngresoEgreso ingresoEgreso = new DetalleIngresoEgreso(null, rootPaneCheckingEnabled);
            ingresoEgreso.cargarDetalleProd(cod);
        } catch (Exception e) {
        }
        this.cargarTabla();
    }//GEN-LAST:event_btnDetalleActionPerformed
    /**
     * @param args the command line arguments
     */
    /*public static void main(String args[]) {
     /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    /*        try {
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
     if ("Nimbus".equals(info.getName())) {
     javax.swing.UIManager.setLookAndFeel(info.getClassName());
     break;
     }
     }
     } catch (ClassNotFoundException ex) {
     java.util.logging.Logger.getLogger(BuscarEnStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     } catch (InstantiationException ex) {
     java.util.logging.Logger.getLogger(BuscarEnStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     } catch (IllegalAccessException ex) {
     java.util.logging.Logger.getLogger(BuscarEnStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     } catch (javax.swing.UnsupportedLookAndFeelException ex) {
     java.util.logging.Logger.getLogger(BuscarEnStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     }
     //</editor-fold>

     /* Create and display the dialog */
    /*  java.awt.EventQueue.invokeLater(new Runnable() {
     public void run() {
     BuscarEnStock dialog = new BuscarEnStock(new javax.swing.JFrame(), true);
     dialog.addWindowListener(new java.awt.event.WindowAdapter() {
     @Override
     public void windowClosing(java.awt.event.WindowEvent e) {
     System.exit(0);
     }
     });
     dialog.setVisible(true);
     }
     });
     }*/
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnDetalle;
    private javax.swing.JButton btnModificar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tablaStock;
    // End of variables declaration//GEN-END:variables

    private Integer getProductoSeleccionado() throws Exception {
        Integer fila, retorno;
        try {
            fila = this.tablaStock.getSelectedRow();
            retorno = (int) this.tablaStock.getValueAt(fila, 0);
        } catch (Exception e) {
            throw new Exception();
        }

        return retorno;

    }
}
